//
//  VRVideoViewController.swift
//  VPai
//
//  Created by vicyuan on 16/12/16.
//  Copyright © 2016年 viatech. All rights reserved.
//

import Foundation
import AVFoundation
import Async
import GLKit
import player360


private let TAG = "VRPreviewController"


class VRPreviewController: VRViewController {
    
    private var outputTexture: GLuint = 0
    private var textureCache: CVOpenGLESTextureCacheRef?
    private let lock: NSLock = NSLock()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    deinit {
        Log.info(TAG, msg: "deinit")
        
    }
    
    func createTextureCacheIfNeed() {
        if textureCache == nil {
            let err: CVReturn = CVOpenGLESTextureCacheCreate(kCFAllocatorDefault, nil, self.context, nil, &textureCache)
            if err != 0 {
                Log.error(TAG, msg: "Error at CVOpenGLESTextureCacheCreate: \(err)")
                abort()
            }
        }
    }
    
    func updateTexture(pixelBuffer: CVPixelBuffer?) -> Bool {
        if !EAGLContext.setCurrentContext(self.context) {
            return false
        }
        
        if pixelBuffer == nil {
            return false
        }
        
        createTextureCacheIfNeed()
        
        objc_sync_enter(lock)
        outputTexture = GLHelpers.loadVideoTexture(pixelBuffer!, textureCache: textureCache!)
        
        // Do processing work on the texture data here
        CVOpenGLESTextureCacheFlush(textureCache!, 0)
        objc_sync_exit(lock)
        
        return true
    }
    
    override func glkView(view: GLKView, drawInRect rect: CGRect) {
        if !EAGLContext.setCurrentContext(self.context) {
            return
        }
        
        if outputTexture != 0 {
            objc_sync_enter(lock)
            vrDelegate?.setMediaTexture(outputTexture)
            
            // draw
            vrDelegate?.OnRendererDrawFrame(self.context, rect: rect)
            GLHelpers.checkGlError("VRVideoViewController.glkView")
            objc_sync_exit(lock)
        } else {
            glClearColor(0, 0, 0, 1.0)
            glClear(GLenum(GL_COLOR_BUFFER_BIT) | GLenum(GL_DEPTH_BUFFER_BIT))
        }
        
    }
}
